﻿//Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved 
//Contact jon.norton@fin-plus.co.uk website <http://www.fin-plus.co.uk/>
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.ComponentModel;
using FinPlusAssembler;
using FinPlusInterfaces;
using FinPlusCompCore;


namespace FinPlusCompProxy
{
    public class QLEngineDefaultCurves : FinPlusComponent
    {
        [State(Test = true)]
        public override bool IsValid { get; set; }

        private enum Params { CurveName, LinkedCurve };
        private readonly IFinPlusComp _instrumentConn, _defaultCurveBuildConn, _instrumentBuildConn;
        private readonly QLAnalytics _analytics;
        private readonly DefaultCurves _defaultCurves;
        private readonly BuildEvent _buildEvents;

        //construct
        public QLEngineDefaultCurves(IFinPlusComp analytics, IFinPlusComp defaultCurveBuilds, IFinPlusComp _instrumentBuilds, IFinPlusComp instruments, BuildEvent buildEvents)
        {
            _analytics = (QLAnalytics)analytics;
            _defaultCurveBuildConn =defaultCurveBuilds;
            _instrumentBuildConn = _instrumentBuilds;
            _instrumentConn = instruments;
            _buildEvents = buildEvents;
            _defaultCurves = new DefaultCurves();

            foreach (var defaultCurveBuild in _defaultCurveBuildConn.Adapter.Values)
            {
                var curveName = defaultCurveBuild[Params.CurveName.ToString()].ToString();
                var insts = _instrumentConn.Adapter.ToList(Params.LinkedCurve.ToString(), curveName, ',');
                _defaultCurves.TryAdd(curveName, new DefaultCurve(_analytics, curveName, defaultCurveBuild, _instrumentBuildConn.Adapter, insts, _buildEvents));
            }

            IsValid = true;
        }

        //common control interface
        public override void Dispose() 
        {
            try
            {
                if (_instrumentConn != null)
                    _instrumentConn.Dispose();
                if (_defaultCurveBuildConn != null)
                    _defaultCurveBuildConn.Dispose();
                if (_analytics != null)
                    _analytics.Dispose();
            }
            catch (Exception e)
            {
                Level.Warning.Log(e.Message, e);
            }
        
        }
    }
}
